package com.aixingfu.sports.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aixingfu.sports.MVP.contract.AllVenueContract;
import com.aixingfu.sports.MVP.contract.SaleContract;
import com.aixingfu.sports.MVP.contract.UserBugCardContract;
import com.aixingfu.sports.MVP.presenter.AllVenuePresenter;
import com.aixingfu.sports.MVP.presenter.SalePresenter;
import com.aixingfu.sports.MVP.presenter.UserBuyCardPresenter;
import com.aixingfu.sports.Model.AllVenueModel;
import com.aixingfu.sports.Model.SaleModel;
import com.aixingfu.sports.Model.UserBuyCardModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.bean.MessageEvent;
import com.aixingfu.sports.view.PopSaleCheckChooseID;
import com.aixingfu.sports.view.PopupWindowCheckChoose;
import com.aixingfu.sports.view.PopupWindowCheckChooseID;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.ConvertUtil;
import com.orie.librarybase.utils.MoneyEditUtils;
import com.orie.librarybase.utils.UserUtils;
import com.vondear.rxtool.RxTimeTool;
import com.vondear.rxtool.view.RxToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//购卡信息
@Route(path = "/main/PurchaseCardInformationActivity")
public class PurchaseCardInformationActivity extends BaseActivity implements AllVenueContract.MyView, UserBugCardContract.MyView, SaleContract.MyView {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_venue)
    TextView tvVenue;
    @BindView(R.id.ll_venue)
    LinearLayout llVenue;
    @BindView(R.id.tv_card_type)
    TextView tvCardType;
    @BindView(R.id.ll_card_type)
    LinearLayout llCardType;
    @BindView(R.id.ed_card_code)
    EditText edCardCode;

    @BindView(R.id.tv_adviser)
    TextView tvAdviser;
    @BindView(R.id.ll_adviser)
    LinearLayout llAdviser;
    @BindView(R.id.tv_usage_mode)
    TextView tvUsageMode;
    @BindView(R.id.ll_usage_mode)
    LinearLayout llUsageMode;
    @BindView(R.id.ed_price)
    EditText edPrice;
    @BindView(R.id.tv_processing_time)
    TextView tvProcessingTime;
    @BindView(R.id.tv_effective_time)
    TextView tvEffectiveTime;
    @BindView(R.id.ed_remarks)
    EditText edRemarks;
    @BindView(R.id.ed_adviser)
    TextView edAdviser;
    @BindView(R.id.tv_adviser_name)
    TextView tvAdviserName;
    @BindView(R.id.ll_adviser_name)
    LinearLayout llAdviserName;
    private AllVenuePresenter allVenuePresenter;
    private UserBuyCardPresenter userBuyCardPresenter;
    private List<AllVenueModel.DataBean> venueList;
    private List<SaleModel.DataBean> saleList;
    private PopupWindowCheckChoose mPopup;
    private ArrayList<String> mList = new ArrayList();
    private PopupWindowCheckChooseID popupWindowCheckChooseID;
    private PopupWindowCheckChooseID mpopupWindowCheckChooseID;
    private PopSaleCheckChooseID popSaleCheckChooseID;
    private String venue_id = "";
    private String  adviser_id= "";
    private String cardTypeId = "";
    private String sale_id = "";
    private String min_price;
    private String max_price;
    private int dayTime;
    private SalePresenter salePresenter;
    private String edprice = "";
    private String type ="";
    private String member_id ="";
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_purchase_card_information;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/PurchaseCardInformationActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString("type", "");
        member_id = bundle.getString("member_id", "");
        allVenuePresenter = new AllVenuePresenter();
        allVenuePresenter.attachView(this);
        allVenuePresenter.getAllVenue();
        userBuyCardPresenter = new UserBuyCardPresenter();
        userBuyCardPresenter.attachView(this);
        salePresenter = new SalePresenter();
        salePresenter.attachView(this);
        mList = getPopList();
        mPopup = new PopupWindowCheckChoose(PurchaseCardInformationActivity.this, mList);
        mPopup.setTagTxt("请选择")//设置顶部title的内容
                .setButtomTxt("取消")//设置底部按钮内容
                .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
        //单选
        mPopup.setOnEventLisenter(positionList -> {
            mPopup.dismiss();
            tvUsageMode.setText(mList.get(positionList.get(0)));
        });
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        tvProcessingTime.setText(df.format(new Date()));
        edAdviser.setText(UserUtils.getUserName(PurchaseCardInformationActivity.this));
        MoneyEditUtils.afterDotTwo(edPrice);
    }

    /**
     * 数据
     *
     * @return
     */
    public ArrayList<String> getPopList() {
        ArrayList<String> popList = new ArrayList<>();
        popList.add("自用");
        popList.add("送人");
        return popList;
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void beforeInit() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_venue, R.id.ll_card_type, R.id.ll_adviser,R.id.ll_adviser_name, R.id.ll_usage_mode, R.id.tv_back, R.id.tv_next})
    public void onViewClicked(View view) {
        String mvenue = tvVenue.getText().toString();
        String adviser = tvAdviser.getText().toString();
        switch (view.getId()) {
            case R.id.ll_venue:
                hideIputKeyboard();
                if (popupWindowCheckChooseID != null){
                    popupWindowCheckChooseID.showPop(tvVenue);
                }
                break;
            case R.id.ll_card_type:
                hideIputKeyboard();
                if (TextUtils.isEmpty(mvenue)) {
                    RxToast.normal(PurchaseCardInformationActivity.this, "请先选择场馆").show();
                } else {
                    ARouter.getInstance().build("/main/SelectCardActivity").withString("venue_id", venue_id).navigation();
                }
                break;
            case R.id.ll_adviser:
                hideIputKeyboard();
                if (TextUtils.isEmpty(mvenue)) {
                    RxToast.normal(PurchaseCardInformationActivity.this, "请先选择场馆").show();
                } else {
//                    popSaleCheckChooseID.showPop(tvAdviser);
                    if (mpopupWindowCheckChooseID != null){
                        mpopupWindowCheckChooseID.showPop(tvAdviser);
                    }
                }
                break;
            case R.id.ll_adviser_name:
                if (TextUtils.isEmpty(adviser)){
                    RxToast.normal(PurchaseCardInformationActivity.this,"请选择会籍场馆").show();
                }else {
                    if (popSaleCheckChooseID != null){
                        popSaleCheckChooseID.showPop(tvAdviserName);
                    }

                }
                break;
            case R.id.ll_usage_mode:
                hideIputKeyboard();
                if (mPopup != null){
                    mPopup.showPop(tvUsageMode);
                }

                break;
            case R.id.tv_back:
                hideIputKeyboard();
                finish();
                break;
            case R.id.tv_next:
                hideIputKeyboard();
                String venue = tvVenue.getText().toString();
                String cardType = tvCardType.getText().toString();
                String edcardcode = edCardCode.getText().toString();
                String edadviser = edAdviser.getText().toString();
                String tvadviser = tvAdviser.getText().toString();
                String tvusagemode = tvUsageMode.getText().toString();
                edprice = edPrice.getText().toString();
                String tvprocessingTime = tvProcessingTime.getText().toString();
                String tveffectiveTime = tvEffectiveTime.getText().toString();
                String edremarks = edRemarks.getText().toString();
                double a= ConvertUtil.convertToDouble(edprice,0.00);
                double dminPrice = ConvertUtil.convertToDouble(min_price, 0.00);
                double dmaxPrice = ConvertUtil.convertToDouble(max_price, 0.00);

                if (TextUtils.isEmpty(venue)) {
                    RxToast.normal(PurchaseCardInformationActivity.this, "请选择场馆").show();
                } else if (TextUtils.isEmpty(cardType)) {
                    RxToast.normal(PurchaseCardInformationActivity.this, "请选择卡种").show();
                }  else if (TextUtils.isEmpty(tvusagemode)) {
                    RxToast.normal(PurchaseCardInformationActivity.this, "请选择使用方式").show();
                } else  if (a < dminPrice || a>dmaxPrice){
                RxToast.normal(PurchaseCardInformationActivity.this, "请输入正确卡价格").show();
            }else if (TextUtils.isEmpty(edprice)){
                    RxToast.normal(PurchaseCardInformationActivity.this, "请输入卡售价").show();
                }else {
                    getUserBuyCard(venue, cardType, edcardcode, edadviser, tvadviser, tvusagemode, edprice, tvprocessingTime, tveffectiveTime, edremarks);
                }
                break;
        }
    }
    public void getUserBuyCard(String venue, String cardType, String edcardcode, String edadviser, String tvadviser, String tvusagemode, String edprice, String tvprocessingTime, String tveffectiveTime, String edremarks) {
        if (userBuyCardPresenter.isViewAttached()) {
            String timestamp = RxTimeTool.string2Timestamp("yyyy-MM-dd", tvprocessingTime);
            int lastTime= Integer.parseInt(timestamp)+dayTime*24*60*60;
            HashMap<String, String> map = new HashMap<>();
            map.put("venue_id", venue_id);
            map.put("card_id", cardTypeId);
            if ("自用".equals(tvusagemode)) {
                map.put("usage_mode", "1");
            } else if ("送人".equals(tvusagemode)) {
                map.put("usage_mode", "2");
            }
            map.put("card_number", edcardcode);
            map.put("card_price", edprice);
            map.put("start_time", tvprocessingTime);
            map.put("end_time", RxTimeTool.stampToDate(String.valueOf(lastTime)));
            map.put("sale_id",sale_id);
            map.put("new_note", edremarks);
            userBuyCardPresenter.getUserBuyCard(map);
        }
    }

    public void getSale() {
        if (salePresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("venue_id", adviser_id);
            salePresenter.getSale(map);
        }
    }

    @Override
    public void showToast(String msg, String state) {

    }
    @Override
    public void setSale(SaleModel data) {
        if (data.getCode() == 1) {
            saleList = data.getData();
            popSaleCheckChooseID = new PopSaleCheckChooseID(PurchaseCardInformationActivity.this, saleList);
            popSaleCheckChooseID.setTagTxt("请选择会籍")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popSaleCheckChooseID.setOnEventLisenter(positionList -> {
                popSaleCheckChooseID.dismiss();
                String userName = UserUtils.getUserName(PurchaseCardInformationActivity.this);
                String name = saleList.get(positionList.get(0)).getName();
                if (userName.equals(name)){
                    RxToast.normal(PurchaseCardInformationActivity.this, "不能选择自己").show();
                }else {
                    tvAdviserName.setText(saleList.get(positionList.get(0)).getName());
                    sale_id = saleList.get(positionList.get(0)).getSale_id();
                }

            });
        }
    }

    @Override
    public void setUserBuyCard(UserBuyCardModel data) {
        if (data.getCode() == 1) {
            ARouter.getInstance().build("/main/PaymentActivity").withString("type",type).withString("member_id",member_id).navigation();
            RxToast.normal(PurchaseCardInformationActivity.this, data.getMessage()).show();
        } else {
            RxToast.normal(PurchaseCardInformationActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void setAllVenue(AllVenueModel data) {
        if (data.getCode() == 1) {
            venueList = data.getData();
            popupWindowCheckChooseID = new PopupWindowCheckChooseID(PurchaseCardInformationActivity.this, venueList);
            popupWindowCheckChooseID.setTagTxt("请选择场馆")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popupWindowCheckChooseID.setOnEventLisenter(positionList -> {
                popupWindowCheckChooseID.dismiss();
                tvVenue.setText(venueList.get(positionList.get(0)).getVenue_name());
                venue_id = venueList.get(positionList.get(0)).getVenue_id();
                tvCardType.setText("");
                cardTypeId = "";

            });
            mpopupWindowCheckChooseID = new PopupWindowCheckChooseID(PurchaseCardInformationActivity.this, venueList);
            mpopupWindowCheckChooseID.setTagTxt("请选择场馆")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            mpopupWindowCheckChooseID.setOnEventLisenter(positionList -> {
                mpopupWindowCheckChooseID.dismiss();
                tvAdviser.setText(venueList.get(positionList.get(0)).getVenue_name());
                adviser_id = venueList.get(positionList.get(0)).getVenue_id();
                tvAdviserName.setText("");
                sale_id = "";
                getSale();
            });
        }
    }
    @Override
    public void showLoading() {
showLoadingDialog();
    }
    @Override
    public void hideLoading() {
dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        tvCardType.setText(event.getMessage());
        cardTypeId = event.getId();
        dayTime = event.getDayTime();
        min_price = event.getMin_price();
        max_price = event.getMax_price();
        if (this.dayTime >= 365) {
            tvEffectiveTime.setText(this.dayTime / 365 + "年");
        } else {
            tvEffectiveTime.setText(this.dayTime + "天");
        }
        Random random = new Random();
        int a=random.nextInt(10);
        edCardCode.setText("0"+ a + getSecondTimestamp(new Date()));

    }

    //关闭软键盘
    public void hideIputKeyboard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销订阅者
        EventBus.getDefault().unregister(this);
    }
    /**
     * 获取精确到秒的时间戳
     * @return
     */
    public static int getSecondTimestamp(Date date){
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0,length-3));
        } else {
            return 0;
        }
    }

}
